package com.doraemon.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;

/***
 * 阿里云OSS文件上传工具类
 * 用于将文件字节数据上传至阿里云OSS指定存储桶
 */
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    // 阿里云OSS的访问域名
    private String endpoint;
    // 阿里云OSS的访问密钥ID
    private String accessKeyId;
    // 阿里云OSS的访问密钥Secret
    private String accessKeySecret;
    // 阿里云OSS的存储桶名称
    private String bucketName;

    /**
     * 文件上传方法
     *
     * @param bytes      文件的字节数组
     * @param objectName 文件在OSS中的存储路径及名称
     * @return 文件在OSS上的完整访问路径
     */
    public String upload(byte[] bytes, String objectName) {

        // 创建OSSClient实例，用于与阿里云OSS进行交互
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 使用OSSClient实例将文件上传到指定的bucket和路径
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            // 捕获并处理OSS服务端异常
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            // 捕获并处理客户端异常
            System.out.println("Caught a ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            // 关闭OSSClient，释放资源
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        // 检查 endpoint 是否包含协议前缀 https:// 或 http://，如果有则去掉
        if (endpoint.startsWith("https://")) {
            endpoint = endpoint.substring(8); // 去掉 "https://"
        } else if (endpoint.startsWith("http://")) {
            endpoint = endpoint.substring(7); // 去掉 "http://"
        }

        // 根据阿里云OSS文件访问规则，生成文件访问URL
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)         // 存储桶名称
                .append(".")
                .append(endpoint) // 访问域名(去除多余的https://)
                .append("/")
                .append(objectName);        // 文件路径及名称

        log.info("文件上传到:{}", stringBuilder.toString());

        return stringBuilder.toString(); // 返回生成的文件访问路径
    }
}